package net.paruo.google.gwt.study_meeting.user_control.client;

import net.paruo.google.gwt.study_meeting.user_control.shared.FieldVerifier;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class UserCreate extends Composite {

	private static UserCreateUiBinder uiBinder = GWT
			.create(UserCreateUiBinder.class);

	interface UserCreateUiBinder extends UiBinder<Widget, UserCreate> {
	}

	@UiField
	TextBox tbName;
	@UiField
	TextBox tbMail;
	@UiField
	PasswordTextBox tbPassword;
	@UiField
	Button btnCreate;

	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);
	private final MessageDialogBox dialog = new MessageDialogBox("ユーザ作成");
	private final ImagePopupPanel panel = new ImagePopupPanel(
			"./image/ajax-loader.gif");

	public UserCreate() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiHandler("btnCreate")
	void onClick(ClickEvent e) {
		final String name = tbName.getText();
		String mailAddress = tbMail.getText();
		String password = tbPassword.getText();

		StringBuilder sb = new StringBuilder();
		if (!FieldVerifier.isValidName(name)) {
			sb.append("ユーザ名は4文字以上必要です。<br />");
		}
		if (!FieldVerifier.isValidMailAddress(mailAddress)) {
			sb.append("不正なメールアドレスです。<br />");
		}
		if (!FieldVerifier.isValidPassword(password)) {
			sb.append("パスワードは半角英数字で6文字以上必要です。<br />");
		}
		if (!"".equals(sb.toString())) {
			dialog.center(sb.toString());
			return;
		}

		UserData data = new UserData();
		data.setName(name);
		data.setMailAddress(mailAddress);
		data.setPassword(password);

		btnCreate.setEnabled(false);
		panel.center();

		greetingService.createUser(data, new AsyncCallback<Void>() {

			@Override
			public void onSuccess(Void result) {
				panel.hide();
				btnCreate.setEnabled(true);

				dialog.center("ユーザ [" + name + "] の作成に成功しました。");
				resetForm();
			}

			@Override
			public void onFailure(Throwable caught) {
				if (caught instanceof DuplicateUserException) {
					panel.hide();
					btnCreate.setEnabled(true);

					dialog.center("ユーザ [" + name + "] は既に存在します。");
					GWT.log("User already exists: " + name, caught);
					resetForm();
					return;
				}
				panel.hide();
				btnCreate.setEnabled(true);

				dialog.center("ユーザ [" + name + "] の作成に失敗しました。");
				GWT.log("Failed to create user: " + name, caught);
				resetForm();
			}
		});
	}

	private void resetForm() {
		tbName.setText("");
		tbMail.setText("");
		tbPassword.setText("");
	}
}
